package com.mjk.manager.amis.core.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.core.jdbc.bean.BeePage;
import com.mjk.common.core.jdbc.service.idgenerator.IdGenerateType;
import com.mjk.common.core.jdbc.service.plus.idbservice.BeeDBService;
import com.mjk.common.core.jdbc.service.plus.wrap.BeeQueryWrapper;
import com.mjk.common.util.ObjectUtils;
import com.mjk.common.util.StrUtils;
import com.mjk.manager.amis.core.dto.AmisCrudDTO;
import com.mjk.manager.amis.core.dto.SessionDetails;
import com.mjk.manager.amis.core.model.PlatUser;
import com.mjk.manager.amis.core.model.SysRole;
import com.mjk.manager.amis.core.model.SysRoleUser;
import com.mjk.manager.amis.core.utils.SessionHolder;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RequestMapping("/mamis/plat/user")
@RestController
@Slf4j
public class PlatUserController {
    @Autowired
    BeeDBService beeDBService;
    @Autowired
    SessionHolder sessionHolder;

    @RequestMapping("/list")
    public BeeResponse getUserList(final HttpServletRequest request,String name,int pageStart,int pageSize) {
        // 查询数据库
        SessionDetails session = sessionHolder.getSession(request);
        if(session == null){
            return BeeError.TOKEN_IS_EXPRIE.tranceError();
        }
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatUser());
        wrapper.eq(PlatUser::getDEF_SYS_ID, sessionHolder.getSystem(request).getId());
        if(ObjectUtils.isNotEmpty(name)){
            wrapper.condition("name like #{1} or login_name like #{1}","%"+name+"%");
        }
        wrapper.setPage(pageStart,pageSize);
        BeePage<PlatUser> users = beeDBService.findManyByWrapperWithPage(wrapper);

        List<String> roleids = users.getList().stream()
                .filter(role -> !ObjectUtils.isEmpty(role.getRoles())) // 过滤掉空值
                .flatMap(item -> Arrays.stream(item.getRoles().split(",")))
                .toList();
        //获取用户角色信息
        if(!CollectionUtils.isEmpty(roleids)) {
            wrapper = BeeQueryWrapper.getWrapper(SysRole.class);
            wrapper.in(SysRole::getId, roleids);
            List<SysRole> roles = beeDBService.findManyByWrapper(wrapper);
            Map<String, String> roleMap = roles.stream()
                    .collect(Collectors.toMap(SysRole::getId, SysRole::getDESCR));
            for (PlatUser user : users.getList()) {
                List<String> sb = new ArrayList<>();
                if (user.getRoles().contains(",")) {
                    for (String role : user.getRoles().split(",")) {
                        sb.add(roleMap.get(role));
                    }
                } else {
                    sb.add(roleMap.get(user.getRoles()));
                }
                user.setRoleName(StrUtils.join(sb, ","));
            }
        }
        // 构造 amis 要求的数据结构
        final AmisCrudDTO<PlatUser> data = new AmisCrudDTO<>();
        data.setItems(users.getList());
        data.setTotal(Long.valueOf(users.getPageTotal()));

        // 返回结果集
        return BeeError.BEE_SUC.tranceError(data);
    }

    @RequestMapping(value = {"", "save"})
    public BeeResponse saveUser(final HttpServletRequest request, @RequestBody final PlatUser obj) {
        final SessionDetails session = sessionHolder.getSession(request);
        if(session == null){
            return BeeError.TOKEN_IS_EXPRIE.tranceError();
        }
        obj.setUPDATED_BY(obj.getCreater());
        int ret = 0;
        if (StrUtil.isNotBlank(obj.getId())) {
            obj.setUPDATED_AT(LocalDateTime.now());
            if(!CollectionUtils.isEmpty(obj.getRoleIds())) {
                obj.setRoles(StrUtils.join(obj.getRoleIds(), ","));
            }
            BeeQueryWrapper wrapper = new BeeQueryWrapper(obj);
            wrapper.eq(PlatUser::getId, obj.getId());
            ret = beeDBService.update(wrapper);
        } else {// insert
            obj.setId(IdGenerateType.AUTO_SNOWFLAKE.getGenerator().getId(obj));
            obj.setCREATED_AT(LocalDateTime.now());
            obj.setUPDATED_AT(LocalDateTime.now());
            obj.setSALT(IdGenerateType.AUTO_UUID.getGenerator().getId(obj));
            obj.setDELETED(false);
            obj.setSTATUS(1);
            obj.setCREATED_BY(obj.getCreater());
            if(!CollectionUtils.isEmpty(obj.getRoleIds())) {
                obj.setRoles(StrUtils.join(obj.getRoleIds(), ","));
            }
            obj.setDEF_SYS_ID(sessionHolder.getSystem(request).getId());

            ret = beeDBService.insert(obj);
        }
        if(!ObjectUtils.isEmpty(obj.getRoleIds())){
            BeeQueryWrapper wrapper = BeeQueryWrapper.getWrapper(SysRoleUser.class)
                    .eq(SysRoleUser::getUSER_ID,obj.getId());
            beeDBService.delete(wrapper);
            for(String roleId : obj.getRoleIds()){
                SysRoleUser su = new SysRoleUser();
                su.setUSER_ID(obj.getId()).setDELETED("0").setCREATED_BY(obj.getCreater())
                        .setROLE_ID(roleId).setCREATED_AT(LocalDateTime.now()).setUPDATED_BY(obj.getCreater())
                        .setUPDATED_AT(LocalDateTime.now())
                        .setId(IdGenerateType.AUTO_SNOWFLAKE.getGenerator().getId(su));
                beeDBService.save(su);
            }
        }
        return ret > 0 ? BeeError.BEE_SUC.tranceError() : BeeError.BEE_FAILD.tranceError();
    }

    @RequestMapping (value = {"/{id}","/delete/{id}"})
    public BeeResponse delUser(final HttpServletRequest request, @PathVariable("id") String id) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(new PlatUser());
        wrapper.eq(PlatUser::getId, id);
        int ret = beeDBService.delete(wrapper);
        return ret > 0 ? BeeError.BEE_SUC.tranceError() : BeeError.BEE_FAILD.tranceError();
    }

    @PostMapping("/password")
    public BeeResponse setUserPassword(final HttpServletRequest request, @RequestBody final PlatUser obj) {
        BeeQueryWrapper wrapper = new BeeQueryWrapper(obj);
        wrapper.eq(PlatUser::getId, obj.getId());
        List<PlatUser> users = beeDBService.findManyByWrapper(wrapper);
        if (CollectionUtils.isEmpty(users)) {
            return BeeError.LOGIN_ERROR_ACCOUNT_NOT_EXIT.tranceError();
        }
        final PlatUser user = users.get(0);

        String salt = user.getSALT();
        if (StrUtil.isBlank(salt)) {
            salt = UUID.randomUUID().toString();
        }

        final String password = SecureUtil.md5(obj.getPASSWORD() + salt);

        final PlatUser entity = new PlatUser();
        entity.setId(obj.getId());
        entity.setPASSWORD(password);
        entity.setSALT(salt);

        int ret = beeDBService.update(wrapper);

        return ret > 0 ? BeeError.BEE_SUC.tranceError() : BeeError.BEE_FAILD.tranceError();
    }

}
